package cmd

import (
	"bufio"
	"fmt"
	"gitee.com/cdsailyj/go-vpn/common/util/vpn"
	"github.com/go-vgo/robotgo"
	"github.com/pion/turn/v2"
	"log"
	"net"
	"os"
	"time"
)

const VPN_DOMAIN = "vpnws.ixintu.com" //"vpnws.ixintu.com"

type VpnWebRtcService struct {
	SignalingClient *vpn.SignalingClient
}

// B电脑控制端主函数
func (t *VpnWebRtcService) Turn() {
	// 监听 UDP 端口
	udpListener, err := net.ListenPacket("udp4", ":3478")
	if err != nil {
		log.Panicf("Failed to create TURN server listener: %s", err)
	}

	// 简单的用户存储
	var users = map[string]string{
		"user1": "password123123",
		"user2": "password123123",
	}
	// 创建 TURN 服务器配置
	_, err = turn.NewServer(turn.ServerConfig{
		Realm: "your-realm.com", // 设置 Realm
		// 设置认证处理器（简单版本，接受所有认证）
		AuthHandler: func(username, realm string, srcAddr net.Addr) ([]byte, bool) {
			// 查找用户
			pass, exists := users[username]
			if !exists {
				fmt.Printf("User not found: %s\n", username)
				return nil, false
			}

			// 返回密码的 MD5 hash（长期认证机制）
			return turn.GenerateAuthKey(username, realm, pass), true
		},
		PacketConnConfigs: []turn.PacketConnConfig{
			{
				PacketConn: udpListener,
				RelayAddressGenerator: &turn.RelayAddressGeneratorStatic{
					RelayAddress: net.ParseIP("101.37.81.144"), // 公网 IP
					Address:      "0.0.0.0",                    // 监听地址
				},
			},
		},
	})
	if err != nil {
		log.Panic(err)
	}

	fmt.Println("TURN Server is running on :3478")

	// 保持服务器运行
	select {}
}

func (t *VpnWebRtcService) VpnClientB() {
	fmt.Println("🔍 开始启动控制端...")

	signaling, err := vpn.NewSignalingClient(VPN_DOMAIN, "danny", "company", false)
	if err != nil {
		log.Fatal("连接信令服务器失败:", err)
	}
	fmt.Println("✅ 信令服务器连接成功")
	t.SignalingClient = signaling

	signaling.SetPeerConnection()

	go func() {
		time.Sleep(5 * time.Second)
		signaling.SendMessage(vpn.Message{
			Type: "start",
			Data: "",
			From: "danny", // 添加From字段
			To:   "company",
		})
	}()

	// 启动HTTP服务器供前端播放视频
	t.waitForExit()
}

// 等待退出命令
func (t *VpnWebRtcService) waitForExit() {
	scanner := bufio.NewScanner(os.Stdin)
	for {
		if scanner.Scan() {
			input := scanner.Text()
			if input == "stop" {
				fmt.Println("👋 停止客户端")
				return
			}
		}
	}
}

// 处理控制指令
func (t *VpnWebRtcService) handleControlCommand(cmd vpn.ControlCommand) {
	fmt.Printf("收到控制指令: %+v\n", cmd)

	switch cmd.Type {
	case "mousemove":
		fmt.Printf("移动鼠标到: (%d, %d)\n", cmd.X, cmd.Y)
		robotgo.Move(cmd.X, cmd.Y)
	case "mouseclick":
		fmt.Printf("鼠标点击: %v\n", cmd.Key)
		robotgo.Click(cmd.Key)
	case "keyboard":
		// 执行键盘操作
		t.executeKeyboardCommand(cmd)
	case "clipboard":
		// 处理剪贴板
		fmt.Printf("设置剪贴板: %s\n", cmd.Text)
		robotgo.WriteAll(cmd.Text)
	case "screen":
		fmt.Printf("切换屏幕: %s \n", cmd.Key)
	}
}

// executeKeyboardCommand 执行键盘控制
func (t *VpnWebRtcService) executeKeyboardCommand(cmd vpn.ControlCommand) {
	fmt.Printf("执行按键: %s\n", cmd.Key)
	// robotgo.KeyTap(cmd.Key)
}
